﻿using System;
using System.Data;
using System.Windows.Forms;
using HRM.HRMServiceProxy;
using WeifenLuo.WinFormsUI.Docking;
using System.Drawing;
using DetailInfo = HRM.BusinessLogic.BhDetailInfo;
using HRM.BusinessLogic;

namespace HRM
{
    public partial class frmDieuChinhTheoNhom : DockContent
    {
        DialogResult dlgResult;
        RoleRightInfo listRole;
        int itemCount = 0;
        int pageSize = UIParamater.pageSize;
        int totalPage = 0;
        int currPage = 0;
        int branch_ID;
        int department_ID = 0;
        //
        int year = 0;
        int month = 0;
        string typeCode = "";
        //
        string BranchCode = "";
        string _selectedID = ",";
        DataTable _dtData = null;
        //
        public delegate void SaveTangLuongHangLoat(DetailInfo detailInfo);
        public event SaveTangLuongHangLoat saveTangLuongHangLoat;


        public string SelectedID
        {
            get { return _selectedID; }
            set { _selectedID = value; }
        }
        private string _FullName;
        public string FullName
        {
            get { return _FullName; }
            set { _FullName = value; }
        }
        string _Code;
        public string Code
        {
            get { return _Code; }
            set { _Code = value; }
        }
        private int _EmployeeID;
        public int EmployeeID
        {
            get { return _EmployeeID; }
            set { _EmployeeID = value; }
        }
        string _SIBookNo;
        public string SIBookNo
        {
            get { return _SIBookNo; }
            set { _SIBookNo = value; }
        }

        BranchClient _wcfBranch;
        EmployeeClient _wcfEmployee;
        public frmDieuChinhTheoNhom()
        {
            InitializeComponent();
            dlgResult = DialogResult.Cancel;

            _wcfEmployee = Service.Employee();
            _wcfBranch = Service.Branch();
            txtKeyWord.Focus();
            

            branch_ID = Program.intBranchID;
            BranchCode = Program.strBranchCode;
            BuildVoucherGrid();
            LoadData();
            cboMucLuong.SelectedIndex = 1;
        }
        public frmDieuChinhTheoNhom(RoleRightInfo _listRole, int year, int month, string typecode)
        {
            InitializeComponent();

            //
            dlgResult = DialogResult.Cancel;
            this.MaximizeBox = true;
            _wcfEmployee = Service.Employee();
            _wcfBranch = Service.Branch();
            txtKeyWord.Focus();
            listRole = _listRole;
            branch_ID = Program.intBranchID;
            this.year = year;
            this.month = month;
            this.typeCode = typecode;
            BranchCode = Program.strBranchCode;
            //
            cboMucLuong.Items.Clear();
            BuildCboMucLuong();
            BuildVoucherGrid();
            UISetting.LoadTreeView3(ref tvBranch);
            //LoadData();
            cboMucLuong.SelectedIndex = 0;
        }

        private void BuildCboMucLuong()
        {
            DataSet ds = _wcfEmployee.Employee_Form02MucLuongDuyNhat(BranchCode, year, month, typeCode);
            cboMucLuong.ComboBox.DisplayMember = "Text";
            cboMucLuong.ComboBox.ValueMember = "Value";
            if (ds != null)
            {
                cboMucLuong.Items.Add(new ComboboxItem("Tất cả", 0));
                //
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    //int i = 1;
                    cboMucLuong.Items.Add(new ComboboxItem(Globals.Object_GetString(dr[0], Globals.CS_MONEY_FORMAT), dr[0]));
                }
            }
            ds.Clear();
            ds.Dispose();
        }

        private void BuildVoucherGrid()
        {
            dgvEmployeeList.Columns.Clear();
            //Thêm cột Checkbox
            DataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn();
            col.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            col.Name = "Check";
            col.HeaderText = "Chọn";
            col.Width = 50;
            col.ThreeState = false;
            col.TrueValue = true;
            col.FalseValue = false;
            col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleLeft;
            dgvEmployeeList.Columns.Add(col);
            col.Visible = true;

            UISetting.AddColumn(ref dgvEmployeeList, "RowNumber", "STT", "C", 50, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_ID", "Mã chính", "", 1, false, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Detail_InsBookNo", UpdateUI.GetString("sosobh"), "C", 90, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_FullName", UpdateUI.GetString("hovaten"), "", 150, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_DateOfBirth", UpdateUI.GetString("ngaysinh"), "", 90, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Detail_InstypeCode", "PA", "C", 60, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Detail_Amount", "Mức lương", "C", 130, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Detail_NewAmout", "Mức lương mới", "C", 130, true, false);
            dgvEmployeeList.Columns["Detail_NewAmout"].DefaultCellStyle.BackColor = Color.Yellow;
            UISetting.AddColumn(ref dgvEmployeeList, "Detail_FromDate", UpdateUI.GetString("tuthang"), "C", 90, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Detail_ToDate", UpdateUI.GetString("denthang"), "C", 90, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Detail_TotalMonth", "Số tháng", "C", 60, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "ten_phongban", "Phòng ban", "C", 60, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "BHXH", "Tỷ lệ thu BHXH", "C", 110, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "BHYT", "Tỷ lệ thu BHYT", "C", 110, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "BHTN", "Tỷ lệ thu BHTN", "C", 110, true, true);
        }

        public void LoadData()
        {
            dgvEmployeeList.Rows.Clear();
            //bool hideCheck = false;
            DataRow[] dr = null;
            currPage = Pager.PageIndex;
            decimal amount = Globals.Object_GetValue<decimal>(((ComboboxItem)(cboMucLuong.SelectedItem)).Value);

            //if (_dtData == null)
                //_dtData = _wcfEmployee.Employee_Form02DieuChinhLuongTheoNhom(BranchCode, year, month, 0).Tables[0];
            _dtData = Employee_Controller.Instance().Employee_DieuChinhLuongTheoNhom(BranchCode, department_ID, year, month, 0);
            string sFilter = amount != 0 ? "Amount = " + amount.ToString() + " AND " : "";
            sFilter += " (Detail_InsBookNo = '" + txtKeyWord.Text.Trim() + "' OR Employee_FullName LIKE '%" + txtKeyWord.Text.Trim() + "%' )";
            dr = _dtData.Select(sFilter);
            //
            if(dr!=null)
            for (int i = 0; i < dr.Length; i++)
            {
                dgvEmployeeList.Rows.Insert(i, 1);
                dgvEmployeeList.Rows[i].Cells["Check"].Value = false;
                dgvEmployeeList.Rows[i].Cells["RowNumber"].Value = i + 1;
                dgvEmployeeList.Rows[i].Cells["Employee_ID"].Value = dr[i]["Employee_ID"].ToString();
                dgvEmployeeList.Rows[i].Cells["Employee_FullName"].Value = dr[i]["Employee_FullName"].ToString();
                dgvEmployeeList.Rows[i].Cells["Employee_DateOfBirth"].Value = Convert.ToString(dr[i]["Employee_DateOfBirth"]);
                dgvEmployeeList.Rows[i].Cells["Detail_InsBookNo"].Value = dr[i]["Detail_InsBookNo"].ToString();
                dgvEmployeeList.Rows[i].Cells["Detail_FromDate"].Value = month.ToString("00") + "/" + year.ToString();
                dgvEmployeeList.Rows[i].Cells["Detail_ToDate"].Value = month.ToString("00") + "/" + year.ToString();
                dgvEmployeeList.Rows[i].Cells["Detail_TotalMonth"].Value = "0";

                dgvEmployeeList.Rows[i].Cells["Detail_InstypeCode"].Value = "DC";
                dgvEmployeeList.Rows[i].Cells["Detail_Amount"].Value = Globals.Object_GetString(dr[i]["Amount"],Globals.CS_MONEY_FORMAT);
                dgvEmployeeList.Rows[i].Cells["ten_phongban"].Value = dr[i]["ten_phongban"].ToString();
//                dgvEmployeeList.Rows[i].Cells["Detail_NewAmout"].Value = dr[i]["Detail_NewAmout"].ToString();
                
                //dgvEmployeeList.Rows[i].Cells["DLNhapDung"].Value = Convert.ToBoolean(dr[i]["DLNhapDung"]) ? "Đúng" : "Sai";
                //
                //Tỷ lệ thu
                dgvEmployeeList.Rows[i].Cells["BHXH"].Value = dr[i]["Detail_SocialRate"];
                dgvEmployeeList.Rows[i].Cells["BHYT"].Value = dr[i]["Detail_MedicalRate"];
                dgvEmployeeList.Rows[i].Cells["BHTN"].Value = dr[i]["Detail_UnemployedRate"];
            }
        }

        private void GetSelectedID()
        {
            dgvEmployeeList.EndEdit();
            foreach (DataGridViewRow row in dgvEmployeeList.Rows)
            {
                if (Convert.ToBoolean(row.Cells["Check"].Value))
                {
                    if (!_selectedID.Contains("," + row.Cells["Employee_ID"].Value.ToString() + ","))
                        _selectedID += row.Cells["Employee_ID"].Value.ToString() + ",";
                }
                else
                {
                    string sOld = "," + row.Cells["Employee_ID"].Value.ToString() + ",";
                    if (_selectedID.Contains(sOld))
                        _selectedID = _selectedID.Replace(sOld, ",");
                }
            }
        }

        private void btnFisrt_Click(object sender, EventArgs e)
        {
            //GetSelectedID();
            currPage = 0;
            LoadData();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            //GetSelectedID();
            if (totalPage > 0 && currPage < totalPage - 1)
                currPage++;
            LoadData();
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            //GetSelectedID();
            if (currPage > 0)
                currPage--;
            LoadData();
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            //GetSelectedID();
            if (totalPage != 0)
                currPage = totalPage - 1;
            LoadData();
        }

        private void dgvEmployeeList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            dlgResult = DialogResult.OK;
            this.Close();
        }

        private void txtKeyWord_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                btnFind_Click(null, null);
        }

        private void btnFind_Click(object sender, EventArgs e)
        {
            //GetSelectedID();
            currPage = 0;
            LoadData();
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            //GetSelectedID();
            if (dgvEmployeeList.SelectedRows.Count > 0)
                dgvEmployeeList_CellDoubleClick(null, null);

        }

        private void frmChooseEmployeeList_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.DialogResult = dlgResult;
        }

        private void ChkCheckAll_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < dgvEmployeeList.Rows.Count; i++)
            {
                dgvEmployeeList.Rows[i].Cells["Check"].Value = chkAll.Checked;
            }
            //GetSelectedID();
        }

        private void cboSoThang_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadData();
        }

        private void btnNew_Click_1(object sender, EventArgs e)
        {
            
            if (FormGlobals.Grid_HasError(dgvEmployeeList))
            {
                return;
            }

            //GetSelectedID();
            //if (_selectedID.Split(new string[]{","},StringSplitOptions.RemoveEmptyEntries).Length > 0)
            //{
            //    dlgResult = DialogResult.OK;
            //    this.Close();
            //}
            //else
            //{
            //    MessageBox.Show("Chưa có dữ liệu nào được chọn!");
            //}
            DetailInfo detailInfo;
            bool HasCheck = false;
            bool HasSave = false;
            dgvEmployeeList.EndEdit();
            foreach (DataGridViewRow dr in dgvEmployeeList.Rows)
            {
                if (Convert.ToBoolean(dr.Cells["Check"].Value))
                {
                    HasCheck = true;
                    //
                    detailInfo = new DetailInfo();
                    detailInfo.Detail_Id = 0;
                    //detailInfo.DocumentID = _DocumentID;
                    detailInfo.Detail_Insbookno = Globals.Object_GetString(dr.Cells["Detail_InsBookNo"].Value, "");
                    //detailInfo.EmployeeCode = employeeInfo.Code;

                    detailInfo.Detail_Fromdate = UISetting.GetDate(Globals.Object_GetString(dr.Cells["Detail_FromDate"].Value, ""));
                    detailInfo.Detail_Todate = UISetting.GetDate(Globals.Object_GetString(dr.Cells["Detail_ToDate"].Value, ""));
                    detailInfo.Detail_Instypecode = "DC";
                    detailInfo.Detail_Socialrate = Globals.Object_GetValue<decimal>(dr.Cells["BHXH"].Value);
                    detailInfo.Detail_Medicalrate = Globals.Object_GetValue<decimal>(dr.Cells["BHYT"].Value);
                    detailInfo.Detail_Unemployedrate = Globals.Object_GetValue<decimal>(dr.Cells["BHTN"].Value);

                    //detailInfo.OldBasicFactor = Globals.Object_GetValue<decimal>(dr.Cells["BHXH"].Value);
                    //detailInfo.OldPositionFactor = UISetting.GetDecimalNo(txtOldPositionFactor.Text);
                    //detailInfo.OldOverFactor = UISetting.GetDecimalNo(txtOldOverFactor.Text);
                    //detailInfo.OldJobFactor = UISetting.GetDecimalNo(txtOldJobFactor.Text);
                    //detailInfo.OldAreaFactor = UISetting.GetDecimalNo(txtOldAreaFactor.Text);
                    //detailInfo.NewBasicFactor = UISetting.GetDecimalNo(txtNewBasicFactor.Text);
                    //detailInfo.NewPositionFactor = UISetting.GetDecimalNo(txtNewPositionFactor.Text);
                    //detailInfo.NewOverFactor = UISetting.GetDecimalNo(txtNewOverFactor.Text);
                    //detailInfo.NewJobFactor = UISetting.GetDecimalNo(txtNewJobFactor.Text);
                    //detailInfo.NewAreaFactor = UISetting.GetDecimalNo(txtNewAreaFactor.Text);

                    //detailInfo.RegionCode = !String.IsNullOrEmpty(employeeInfo.MedicalRegionCode) ? employeeInfo.MedicalRegionCode : Program.strRegionCode;

                    //detailInfo.HospitalCode = _MedicalPlace;

                    detailInfo.Detail_Newamount = Globals.Object_GetValue<decimal>(dr.Cells["Detail_NewAmout"].Value);
                    detailInfo.Detail_Oldamount = Globals.Object_GetValue<decimal>(dr.Cells["Detail_Amount"].Value);
                    detailInfo.Detail_Type = "ML";
                    detailInfo.Detail_Takecard = false;
                    detailInfo.Detail_Status = 2;
                    detailInfo.Detail_Totalmonth = 0;
                    //detailInfo.BasicSalary = _BasicSalary;
                    //detailInfo.Description = "";
                    //
                    if (saveTangLuongHangLoat != null)
                    {
                        HasSave = true;
                        saveTangLuongHangLoat(detailInfo);
                    }
                }
            }
            if (!HasCheck)
            {
                MessageBox.Show("Bạn phải chọn bản ghi nhân sự cần tăng lương");
                return;
            }
            if(HasSave)
            {
                this.Close();
            }
        }

        private void dgvEmployeeList_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewCell cell = dgvEmployeeList.Rows[e.RowIndex].Cells[e.ColumnIndex];
            
            if ( cell.OwningColumn.Name.ToUpper() == "DETAIL_NEWAMOUT")
            {
                if (cell.Value != null)
                {
                    decimal newAmount = Globals.Object_GetValue<decimal>(cell.Value);
                    cell.ErrorText = newAmount > 0 ? "" : "Mức lương mới không hợp lệ";
                    if (newAmount > 0 && e.RowIndex == 0)
                    {
                        decimal preAmount = cell.Tag != null ? Globals.Object_GetValue<decimal>(cell.Tag) : 0; ;
                        if (preAmount != newAmount)
                            cell.Tag = newAmount;
                        cell.Value = Globals.Object_GetString(newAmount, Globals.CS_MONEY_FORMAT);

                        if (preAmount != newAmount && MessageBox.Show("Bạn có muốn áp dụng mức lương này cho tất cả", "Tăng mức lương hàng loạt", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            foreach (DataGridViewRow dgvr in dgvEmployeeList.Rows)
                            {
                                dgvr.Cells["DETAIL_NEWAMOUT"].Value = Globals.Object_GetString(newAmount, Globals.CS_MONEY_FORMAT);
                            }
                        }
                    }
                }
                else
                    cell.ErrorText = "";
            }
        }

        private void dgvEmployeeList_KeyDown(object sender, KeyEventArgs e)
        {
            FormGlobals.Grid_CopyPaste((DataGridView)sender, e);
        }

        private void btnFind_Click_1(object sender, EventArgs e)
        {
            LoadData();
        }

        private void tvBranch_AfterSelect(object sender, TreeViewEventArgs e)
        {
            txtKeyWord.Text = "";
            DataTable dt = new DataTable();
            if (e.Node.Level == 0)
            {
                if (Program.isAdmin || Program.isViewAll)
                    branch_ID = 0;
                else
                    branch_ID = Program.intBranchID;
                BranchCode = _wcfBranch.Branch_GetInfo(branch_ID).Code;
                department_ID = 0;
                LoadData();
            }
            else if (e.Node.Level == 1)
            {
                branch_ID = Convert.ToInt32(e.Node.Tag);
                department_ID = 0;
                BranchCode = _wcfBranch.Branch_GetInfo(branch_ID).Code;
                currPage = 0;
                LoadData();
            }
            else if (e.Node.Level >= 2)
            {
                department_ID = Convert.ToInt32(e.Node.Tag);
                branch_ID = Convert.ToInt32(e.Node.Parent.Tag);
                BranchCode = _wcfBranch.Branch_GetInfo(branch_ID).Code;
                currPage = 0;
                LoadData();
            }
        }
    }
}

